<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.9.0">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!--Description-->
    
        <meta name="description" content="整理django中Auth模块from django.contrib import auth
一.设置默认Auth表单
auth默认是使用自带的user表单
自定义Auth表单一定要在settings.py中告诉Django，我现在使用我新定义的UserInfo表来做用户认证。写法如下：
12# 引">
    

    <!--Author-->
    
        <meta name="author" content="ck">
    

    <!--Open Graph Title-->
    
        <meta property="og:title" content="Django中的Auth模块">
    

    <!--Open Graph Description-->
    

    <!--Open Graph Site Name-->
    <meta property="og:site_name" content="CK&#39;s blogs">

    <!--Type page-->
    
        <meta property="og:type" content="article">
    

    <!--Page Cover-->
    

    <meta name="twitter:card" content="summary">
    

    <!-- Title -->
    
    <title>Django中的Auth模块 - CK&#39;s blogs</title>

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

    <!-- Custom Fonts -->
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- Gallery -->
    <link href="//cdnjs.cloudflare.com/ajax/libs/featherlight/1.3.5/featherlight.min.css" type="text/css" rel="stylesheet">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/blog/css/style.css">

    <!-- Google Analytics -->
    


</head>


<body>

<div class="bg-gradient"></div>
<div class="bg-pattern"></div>

<!-- Menu -->
<!--Menu Links and Overlay-->
<div class="menu-bg">
    <div class="menu-container">
        <ul>
            
            <li class="menu-item">
                <a href="/blog/">
                    Home
                </a>
            </li>
            
            <li class="menu-item">
                <a href="/blog/archives">
                    Archives
                </a>
            </li>
            
            <li class="menu-item">
                <a href="/blog/2019/09/04/本人简历/">
                    About
                </a>
            </li>
            
            <li class="menu-item">
                <a href="/blog/tags">
                    Tags
                </a>
            </li>
            
            <li class="menu-item">
                <a href="/blog/categories">
                    Categories
                </a>
            </li>
            
            <li class="menu-item">
                <a href="/blog/contact.html">
                    Contact
                </a>
            </li>
            
        </ul>
    </div>
</div>

<!--Hamburger Icon-->
<nav>
    <a href="#menu"></a>
</nav>

<div class="container">

    <!-- Main Content -->
    <div class="row">
    <div class="col-sm-12">

        <!--Title and Logo-->
        <header>
    <div class="logo">
        <a href="/blog/"><i class="logo-icon fa fa-cube" aria-hidden="true"></i></a>
        
    </div>
</header>

        <section class="main">
            
<div class="post">

    <div class="post-header">
        <h1 class="title">
            <a href="/blog/2019/09/09/Django中的Auth模块/">
                Django中的Auth模块
            </a>
        </h1>
        <div class="post-info">
            
                <span class="date">2019-09-09</span>
            
            
            
        </div>
    </div>

    <div class="content">

        <!-- Gallery -->
        

        <!-- Post Content -->
        <h1 id="整理django中Auth模块"><a href="#整理django中Auth模块" class="headerlink" title="整理django中Auth模块"></a>整理django中Auth模块</h1><p><code>from django.contrib import auth</code></p>
<h2 id="一-设置"><a href="#一-设置" class="headerlink" title="一.设置"></a>一.设置</h2><p>默认Auth表单</p>
<p><code>auth</code>默认是使用自带的<code>user</code>表单</p>
<h3 id="自定义Auth表单"><a href="#自定义Auth表单" class="headerlink" title="自定义Auth表单"></a>自定义Auth表单</h3><p>一定要在<code>settings.py</code>中告诉<code>Django</code>，我现在使用我新定义的<code>UserInfo</code>表来做用户认证。写法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># 引用Django自带的User表，继承使用时需要设置</span><br><span class="line">AUTH_USER_MODEL = &quot;app名.UserInfo&quot;</span><br></pre></td></tr></table></figure>

<p>在<code>modles.py</code>创建表单模型可以对<code>AbstractUser</code>进行继承因为我们可以从源码中看出来auth自带的user表示继承<code>AbstractUser</code>类,所有我们可以可以同样继承然后对于他的内容进行自定义</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth.models import AbstractUser</span><br><span class="line">class UserInfo(AbstractUser):</span><br><span class="line">    新增的内容</span><br><span class="line">    通过源码我们可以看出自带的几个内容</span><br></pre></td></tr></table></figure>

<p><code>AbstractUser</code>自带的字段</p>
<p><code>源码里的内容</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">username :账号</span><br><span class="line">first_name:姓</span><br><span class="line">last_name:名</span><br><span class="line">email:邮箱</span><br><span class="line">is_staff ： 用户是否拥有网站的管理权限.</span><br><span class="line">is_active： 是否允许用户登录, 设置为 False，可以在不删除用户的前提下禁止用户登录。</span><br><span class="line">date_joined:创建日期</span><br></pre></td></tr></table></figure>

<p>再看他的父级<code>AbstractBaseUser</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">password:密码</span><br><span class="line">last_login:最后一次登入时间</span><br><span class="line">is_active:是否允许用户登录, 设置为 False，可以在不删除用户的前提下禁止用户登录。</span><br></pre></td></tr></table></figure>

<p>再看他的另外的父级<code>PermissionsMixin</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">is_superuser:是否为超级账号也就管理员</span><br><span class="line">groups:分组</span><br><span class="line">user_permissions:用户权限</span><br></pre></td></tr></table></figure>

<p>我们可以再这基础上进行新增</p>
<h2 id="二-注册相关"><a href="#二-注册相关" class="headerlink" title="二.注册相关"></a>二.注册相关</h2><h3 id="创建普通用户"><a href="#创建普通用户" class="headerlink" title="创建普通用户"></a>创建普通用户</h3><p><code>create_user()</code></p>
<p>auth 提供的一个创建新用户的方法，需要提供必要参数（username、password）等。</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth.models import User</span><br><span class="line">user = User.objects.create_user（username=&apos;用户名&apos;,password=&apos;密码&apos;,email=&apos;邮箱&apos;,...）</span><br></pre></td></tr></table></figure>

<h3 id="创建超级用户"><a href="#创建超级用户" class="headerlink" title="创建超级用户"></a>创建超级用户</h3><p><code>create_superuser()</code></p>
<p>auth 提供的一个创建新的超级用户的方法，需要提供必要参数（username、password）等。</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth.models import User</span><br><span class="line">user = User.objects.create_superuser（username=&apos;用户名&apos;,password=&apos;密码&apos;,email=&apos;邮箱&apos;,...）</span><br></pre></td></tr></table></figure>

<h2 id="三-登入相关"><a href="#三-登入相关" class="headerlink" title="三.登入相关"></a>三.登入相关</h2><h3 id="验证登入"><a href="#验证登入" class="headerlink" title="验证登入"></a>验证登入</h3><p><code>authenticate()</code></p>
<p>提供了用户认证功能，即验证用户名以及密码是否正确，一般需要username 、password两个关键字参数。</p>
<p>如果认证成功（用户名和密码正确有效），便会返回一个 User 对象。</p>
<p>authenticate()会在该 User 对象上设置一个属性来标识后端已经认证了该用户，且该信息在后续的登录过程中是需要的。</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">user = authenticate(username=&apos;usernamer&apos;,password=&apos;password&apos;)</span><br></pre></td></tr></table></figure>

<h3 id="将登入的对象存放在request中"><a href="#将登入的对象存放在request中" class="headerlink" title="将登入的对象存放在request中"></a>将登入的对象存放在request中</h3><p><code>login(HttpRequest, user)</code></p>
<p>该函数接受一个HttpRequest对象，以及一个经过认证的User对象。</p>
<p>该函数实现一个用户登录的功能。它本质上会在后端为该用户生成相关session数据。</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth import authenticate, login</span><br><span class="line">   </span><br><span class="line">def my_view(request):</span><br><span class="line">  username = request.POST[&apos;username&apos;]</span><br><span class="line">  password = request.POST[&apos;password&apos;]</span><br><span class="line">  user = authenticate(username=username, password=password)</span><br><span class="line">  if user is not None:</span><br><span class="line">    login(request, user)</span><br><span class="line">    # Redirect to a success page.</span><br><span class="line">    ...</span><br><span class="line">  else:</span><br><span class="line">    # Return an &apos;invalid login&apos; error message.</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>

<p>这样设置之后可以直接<code>request.user</code>点出其<code>账号相关信息</code></p>
<p><code>is_authenticated</code>为<code>True</code></p>
<h3 id="将登入的对象存放在request中去除"><a href="#将登入的对象存放在request中去除" class="headerlink" title="将登入的对象存放在request中去除"></a>将登入的对象存放在request中去除</h3><p><code>logout(request)</code></p>
<p>该函数接受一个HttpRequest对象，无返回值。</p>
<p>当调用该函数时，当前请求的session信息会全部清除。该用户即使没有登录，使用该函数也不会报错。</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth import logout</span><br><span class="line">   </span><br><span class="line">def logout_view(request):</span><br><span class="line">  logout(request)</span><br><span class="line">  # Redirect to a success page.</span><br></pre></td></tr></table></figure>

<p>这样设置之后可以直接<code>request.user</code>就为空</p>
<p><code>is_authenticated</code>为<code>False</code></p>
<h3 id="通过认证"><a href="#通过认证" class="headerlink" title="通过认证"></a>通过认证</h3><p><code>is_authenticated()</code></p>
<p>用来判断当前请求是否通过了认证。</p>
<p>用法:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">def my_view(request):</span><br><span class="line">  if not request.user.is_authenticated():</span><br><span class="line">    return redirect(&apos;%s?next=%s&apos; % (settings.LOGIN_URL, request.path))</span><br></pre></td></tr></table></figure>

<p>页面中操作</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;% if request.user.is_authenticated %&#125;</span><br><span class="line">    如果里面有通过验证的user就为真没有就没否</span><br></pre></td></tr></table></figure>

<h2 id="四-登入装饰器"><a href="#四-登入装饰器" class="headerlink" title="四.登入装饰器"></a>四.登入装饰器</h2><p><code>login_requierd()</code></p>
<p>auth 给我们提供的一个装饰器工具，用来快捷的给某个视图添加登录校验。</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">from django.contrib.auth.decorators import login_required</span><br><span class="line">      </span><br><span class="line">@login_required</span><br><span class="line">def my_view(request):</span><br><span class="line">  ...</span><br></pre></td></tr></table></figure>

<p>若用户没有登录，则会跳转到django默认的 登录URL ‘/accounts/login/ ‘ 并传递当前访问url的绝对路径 (登陆成功后，会重定向到该路径)。</p>
<p>如果需要自定义登录的URL，则需要在settings.py文件中通过LOGIN_URL进行修改。</p>
<p>示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LOGIN_URL = &apos;/login/&apos;  # 这里配置成你项目登录页面的路由</span><br></pre></td></tr></table></figure>

<h2 id="五-密码相关"><a href="#五-密码相关" class="headerlink" title="五.密码相关"></a>五.密码相关</h2><h3 id="检验密码是否正确"><a href="#检验密码是否正确" class="headerlink" title="检验密码是否正确"></a>检验密码是否正确</h3><p><code>check_password(password)</code></p>
<p>auth 提供的一个检查密码是否正确的方法，需要提供当前请求用户的密码。</p>
<p>密码正确返回True，否则返回False。</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ok = user.check_password(&apos;密码&apos;)</span><br></pre></td></tr></table></figure>

<h3 id="修改密码"><a href="#修改密码" class="headerlink" title="修改密码"></a>修改密码</h3><p><code>set_password(password)</code></p>
<p>auth 提供的一个修改密码的方法，接收 要设置的新密码 作为参数。</p>
<p>注意：设置完一定要调用用户对象的save方法！！！</p>
<p>用法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">user.set_password(password=&apos;&apos;)</span><br><span class="line">user.save()</span><br></pre></td></tr></table></figure>

<h2 id="六-注意"><a href="#六-注意" class="headerlink" title="六.注意"></a>六.注意</h2><p><code>上面的写的都是基于auth自带的user表达写的</code></p>
<p>导入</p>
<p><code>from django.contrib.auth.models import User</code></p>
<p>如果是自定义表单,请把<code>user换成你自定义的表单名称</code></p>

    </div>

    

    
        <div class="post-tags">
            <i class="fa fa-tags" aria-hidden="true"></i>
            <a href="/blog/tags/Django-Auth/">#Django+Auth</a> <a href="/blog/tags/Django/">#Django</a>
        </div>
    

    <!-- Comments -->
    

</div>
        </section>

    </div>
</div>


</div>

<!-- Footer -->
<div class="push"></div>

<footer class="footer-content">
    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 footer-about">
                <h2>About</h2>
                <p>
                    This theme was developed by <a href="https://github.com/klugjo">Jonathan Klughertz</a>. The source code is available on Github. Create Websites. Make Magic.
                </p>
            </div>
            
    <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3 recent-posts">
        <h2>Recent Posts</h2>
        <ul>
            
            <li>
                <a class="footer-post" href="/blog/2019/10/25/tars框架环境基础搭建/">tars框架环境基础搭建</a>
            </li>
            
            <li>
                <a class="footer-post" href="/blog/2019/10/20/认识tars框架/">认识tars框架</a>
            </li>
            
            <li>
                <a class="footer-post" href="/blog/2019/10/05/redis数据迁移备份与恢复/">redis数据迁移备份与恢复</a>
            </li>
            
            <li>
                <a class="footer-post" href="/blog/2019/09/21/负载均衡的5种策略/">负载均衡的5种策略</a>
            </li>
            
        </ul>
    </div>



            
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <ul class="list-inline footer-social-icons">
                    
                    <li class="list-inline-item">
                        <a href="https://github.com/klugjo/hexo-theme-alpha-dust">
                            <span class="footer-icon-container">
                                <i class="fa fa-github"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="https://twitter.com/?lang=en">
                            <span class="footer-icon-container">
                                <i class="fa fa-twitter"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="https://www.facebook.com/">
                            <span class="footer-icon-container">
                                <i class="fa fa-facebook"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="https://www.instagram.com/">
                            <span class="footer-icon-container">
                                <i class="fa fa-instagram"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="https://dribbble.com/">
                            <span class="footer-icon-container">
                                <i class="fa fa-dribbble"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="https://plus.google.com/">
                            <span class="footer-icon-container">
                                <i class="fa fa-google-plus"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="https://www.behance.net/">
                            <span class="footer-icon-container">
                                <i class="fa fa-behance"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="https://500px.com/">
                            <span class="footer-icon-container">
                                <i class="fa fa-500px"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="mailto:test@example.com">
                            <span class="footer-icon-container">
                                <i class="fa fa-envelope-o"></i>
                            </span>
                        </a>
                    </li>
                    
                    
                    <li class="list-inline-item">
                        <a href="\#">
                            <span class="footer-icon-container">
                                <i class="fa fa-rss"></i>
                            </span>
                        </a>
                    </li>
                    
                </ul>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <div class="footer-copyright">
                    @Untitled. All right reserved | Design & Hexo <a href="http://www.codeblocq.com/">Jonathan Klughertz</a>
                </div>
            </div>
        </div>
    </div>
</footer>

<!-- After footer scripts -->

<!-- jQuery -->
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>

<!-- Tween Max -->
<script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.18.5/TweenMax.min.js"></script>

<!-- Gallery -->
<script src="//cdnjs.cloudflare.com/ajax/libs/featherlight/1.3.5/featherlight.min.js" type="text/javascript" charset="utf-8"></script>

<!-- Custom JavaScript -->
<script src="/blog/js/main.js"></script>

<!-- Disqus Comments -->



</body>

</html>